package cksclient

import (
    "errors"
    "fcs-api/src/app/model"
    "fcs-api/src/client/cks/resource"
    "fmt"

    "github.com/emicklei/go-restful"
    "git.inspur.com/x/common/loggerfactory"
    "git.inspur.com/x/common/rest"
)

var logger = loggerfactory.GetLogger()

func InitCksService(iamTokenApi string) error {
    if iamTokenApi == "" {
        return errors.New("iamTokenApi is nil")
    }
    tokenRestConfig := rest.Config{Host: iamTokenApi, ContentConfig: rest.ContentConfig{ContentType: restful.MIME_JSON}}
    tokenRestConfig.APIPath = "/auth/v1"
    tokenRestConfig.Insecure = true
    tokenClient, err := rest.RESTClientFor(&tokenRestConfig)
    if err != nil {
        return fmt.Errorf("init iamTokenApi error: %v", err)
    }
    Client = &cksClient{tokenClient: tokenClient}
    return nil
}

//go:generate mockgen -destination mocks/mock_cks.go -package client fcs-api/src/client/cks/client Interface
type Interface interface {
    GetAuthToken(userPassword *resource.UserPassword) (*resource.UserAuthToken, error)
    GetTokenByClient(userInfo *resource.UserName) (*resource.UserAuthToken, error)
}

var Client Interface

type cksClient struct {
    tokenClient rest.Interface
}

func (c *cksClient) GetAuthToken(userPassword *resource.UserPassword) (*resource.UserAuthToken, error) {
    authToken := &resource.UserAuthToken{}
    if c.tokenClient == nil {
        return nil, logger.Error("restClient is nil")
    }
    /*userPasswordJSON, _ := json.Marshal(userPassword)
      logger.Debug("userPasswordJSON is %s", userPasswordJSON)*/
    err := c.tokenClient.Post().Resource("/token").Body(userPassword).SetHeader("Content-Type", restful.MIME_JSON).Do().Into(authToken)
    if err != nil {
        _ = logger.Error("GetAuthToken error: %v", err)
        return nil, err
    }
    /*authTokenJSON, _ := json.Marshal(authToken)
      logger.Debug("authTokenJSON is %s", authTokenJSON)*/
    return authToken, nil
}

func (c *cksClient) GetTokenByClient(userInfo *resource.UserName) (*resource.UserAuthToken, error) {

    authToken := &resource.UserAuthToken{}
    if c.tokenClient == nil {
        logger.Error("restClient is nil")
        return nil, errors.New("restClient is nil")
    }
    token, err := model.Base.KeycloakClient.ClientToken()
    if err != nil {
        logger.Error("get client token err %s", err.Error())
        return nil, err
    }
    err = c.tokenClient.Post().Resource("/mock-user").Body(userInfo).
        SetHeader("Authorization", "bearer "+token.AccessToken).
        SetHeader("Content-Type", restful.MIME_JSON).Do().Into(authToken)
    if err != nil {
        _ = logger.Error("GetAuthToken error: %v", err)
        return nil, err
    }
    return authToken, nil
}
